import ChooseGroups, { type GroupMap, type QywxMap } from '@/desktop/components/ChooseGroups'
import { type BaseGroup } from '@/services/contact-types'

export type { QywxMap, GroupMap }

export default function ChooseGroupsToJoin(props: {
  combine?: boolean // 为 true 则多个企业微信的拥有的同一个群合并展示/选择
  sortable?: boolean // 是否开启“已选中的群”的排序
  qywxs?: QywxMap
  groups?: GroupMap
  wxids?: string | string[] // 若指定，则只列出这些企业微信所在的群

  choosed: string[]
  setChoosed: (choosed: string[]) => void

  extendPrefix?: JSX.Element
  extendView?: JSX.Element
}) {
  const {
    combine = false,
    sortable = false,
    qywxs,
    groups,
    wxids,
    choosed,
    setChoosed,
    extendPrefix,
    extendView,
  } = props

  const filterGroup = useMemo(() => {
    const formattedWxids =
      wxids === undefined ? null : new Set(typeof wxids === 'string' ? [wxids] : wxids)
    return (group: BaseGroup) => {
      if (!group.isExternal) return false // 只有外部群可拉人进群
      if (formattedWxids && !formattedWxids.has(group.ownerWxid)) return false
      return true
    }
  }, [wxids])

  const groupInput = groups ? groups.filter(filterGroup) : filterGroup

  return <ChooseGroups
    combine={combine}
    sortable={sortable}
    qywxs={qywxs}
    groups={groupInput}
    choosed={choosed}
    setChoosed={setChoosed}
    choosedSuffix={
      <>
        {extendPrefix ?? null}
        {extendView ?? null}
      </>
    }
  />
}
